package com.xiaowo.backend.module.depend.taobaoopen.util;

import com.xiaowo.backend.module.depend.taobaoopen.entity.PlatformOrderInfo;
import com.xiaowo.backend.module.depend.taobaoopen.entity.TBOrderRate;
import com.xiaowo.backend.utils.DateUtils;
import com.xiaowo.backend.utils.EnDecryptUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author: 
 * @date: 2024-03-10 12:32:43
 * @version" V1.0
 * @description: 红包检测工具-核心代码
 * @modified By:
 **/
public class OrderRedpacketDetectUtil {
    static Logger log = LoggerFactory.getLogger(OrderRedpacketDetectUtil.class);
    //约定的APP_KEY
    public static String APP_KEY = "{}";

    public static String getSign() {
        long time = System.currentTimeMillis() / 1000 / 60;
        return Base64Util.encryptString(EnDecryptUtil.MD5(EnDecryptUtil.MD5(time + APP_KEY)));
    }

    static public class Base64Util {

        private static BASE64Encoder encoder = new BASE64Encoder();
        private static BASE64Decoder decoder = new BASE64Decoder();

        public Base64Util() {}

        public static String encryptString(String str) {
            byte[] b = null;
            String s = null;

            try {
                b = str.getBytes("utf-8");
            } catch(UnsupportedEncodingException var4) {
                var4.printStackTrace();
            }

            if (b != null) {
                s = encoder.encode(b);
            }
            return s;
        }
    }
    public static String getRequest(String url) throws Exception{
        String content = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet();
            httpGet.setURI(new URI(url));

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            content = sb.toString();
        }catch (Exception e){

        }finally {
            if(response !=null ){
                response.close();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        }

        return content;
    }



    public static final int MAX_TRY_TIMES = 3;
    public static final String[] domains = new String[]{
            "http://api.t1.com",
            "http://api.t2.com"
    };
    public static PlatformOrderInfo detectTBOrderByTid(String accessToken, String payOrderId){
        PlatformOrderInfo orderInfo = null;
        for(int i = 0;i< MAX_TRY_TIMES ; i++) {
            try {
                String sign = getSign();
                String fileds = "tid,type,status,payment,buyer_nick,orders,receiver_name,created,pay_time," +
                        "receiver_name," +
                        "receiver_state," +
                        "receiver_city," +
                        "receiver_district," +
                        "receiver_address," +
                        "receiver_mobile," +
                        "receiver_phone," +
                        "service_tags,logistics_infos," +
                        "delivery_time," +//发货时间
                        "sign_time," +//签收时间
                        "seller_memo," +//卖家备注
                        "seller_flag," +//卖家备注插旗
                        "credit_card_fee," +//
                        "received_payment," +//卖家实际收到的支付宝打款金额
                        "pay_channel," +
                        "type," +
                        "trade_attr," +
                        "trade_from," +
                        "buyer_rate";//买家是否已评价
                String req = URLEncoder.encode("{\"fields\":\"" + fileds + "\"," +
                        "\"tid\":\"" + payOrderId + "\"}", "utf-8");
                String url = domains[i % (domains.length)]+"/Api.aspx?action=executeTopApi&methodName=taobao.trade.fullinfo.get" +
                        "&requestObjectJson=" + req + "&SessionKey=" + accessToken + "&sign=" + sign;
                String content = getRequest(url);
                JSONObject json = JSONObject.fromObject(content);
                log.warn("all content json ---->" + content);
                JSONObject body = JSONObject.fromObject(json.getString("Body"));

                JSONObject tradeJ = body.getJSONObject("trade_fullinfo_get_response").getJSONObject("trade");
                double payment = tradeJ.getDouble("payment");//支付金额
                String status = tradeJ.getString("status");//订单状态
                String tid = tradeJ.getString("tid");//宝贝ID
                String buyerNick = tradeJ.getString("buyer_nick");//买家旺旺ID
                String created = tradeJ.getString("created");//订单创建时间
                String payTime = tradeJ.getString("pay_time");//订单支付时间
                Boolean buyerRate = tradeJ.containsKey("buyer_rate") ? tradeJ.getBoolean("buyer_rate") : null;//买家是否评价

             


                //默认卖家不备注的情况下，seller_flag=0, 但是没有返回seller_memo字段
                int seller_flag = tradeJ.getInt("seller_flag");

                String seller_memo = null;
                if (tradeJ.containsKey("seller_memo")) {
                    seller_memo = tradeJ.getString("seller_memo");
                }

                JSONArray ordersJArray = tradeJ.getJSONObject("orders").getJSONArray("order");


                JSONObject orderJ = ordersJArray.getJSONObject(0);
                long num_iid = orderJ.getLong("num_iid");
                String refund_status = orderJ.getString("refund_status");//退款状态
                String price = orderJ.getString("price");//宝贝价格
                String picPath = orderJ.getString("pic_path");//宝贝主图
                String title = orderJ.getString("title");


                orderInfo = new PlatformOrderInfo();
                orderInfo.setNumIid(num_iid);
                orderInfo.setPayment(String.valueOf(payment));
                orderInfo.setPrice(price);
                orderInfo.setTid(tid);
                orderInfo.setBuyerNick(buyerNick);
                orderInfo.setStatus(status);
                orderInfo.setRefundStatus(refund_status);
                orderInfo.setPicPath(picPath);
                orderInfo.setCreated(created);
                orderInfo.setPayTime(payTime);
                orderInfo.setTitle(title);

                orderInfo.setReceiverName(receiver_name);
                orderInfo.setReceiverMobile(receiver_mobile);
                orderInfo.setReceiverPhone(receiver_phone);
                orderInfo.setReceiverState(receiver_state);
                orderInfo.setReceiverCity(receiver_city);
                orderInfo.setReceiverDistrict(receiver_district);
                orderInfo.setReceiverAddress(receiver_address);


                orderInfo.setSellerFlag(seller_flag);
                orderInfo.setSellerMemo(seller_memo);

                orderInfo.setBuyerRate(buyerRate);
                break;

            } catch (Exception e) {
                log.error("核对订单出错：授权{}--支付订单号{}", accessToken, payOrderId);
                e.printStackTrace();
            }
        }
        return orderInfo;
    }

    public static JSONObject memoOrder(String accessToken,
                                       String payOrderNo,
                                       Byte memoFlag,
                                       String memoContent,
                                       boolean add) {
        try {
            String memoSign = getSign();
            String req = URLEncoder.encode("{\"tid\":" + payOrderNo + ",\"memo\":\"" + memoContent + "\"," +
                    "\"flag\":\"" + memoFlag + "\"}", "utf-8");
            log.warn("======================>req memo order<===================" +
                    "{\"tid\":" + payOrderNo + ",\"memo\":\"" + memoContent + "\"," +
                    "\"flag\":\"" + memoFlag + "\"}"
            );

            String url = "";
            if (add) {//新增备注
                url = "http://api.t1.com/Api.aspx?action=executeTopApi&methodName=taobao.trade.memo.add" +
                        "&requestObjectJson=" + req + "&SessionKey=" + accessToken + "&sign=" + memoSign;
            } else {//修改备注
                url = "http://api.t1.com/Api.aspx?action=executeTopApi&methodName=taobao.trade.memo.update" +
                        "&requestObjectJson=" + req + "&SessionKey=" + accessToken + "&sign=" + memoSign;
            }
            log.warn("======================>req memo order<===============" + url);
            String content = getRequest(url);
            log.warn("订单备注结果：{},", content);
            net.sf.json.JSONObject r = net.sf.json.JSONObject.fromObject(content);
            if (r.containsKey("IsError") && !r.getBoolean("IsError")) {
                return r;
            } else {
                log.warn("订单备注失败");
            }

        }catch (Exception e){
            log.error("订单备注{}失败，{}",accessToken,payOrderNo);
            e.printStackTrace();
        }
        return  null;
    }





    public static void main(String[] args) throws  Exception{
        OrderRedpacketDetectUtil tbOrderUtilV2 = new OrderRedpacketDetectUtil();
        String sign = tbOrderUtilV2.getSign();
        String accessToken = "62028024550daf701815994563";

        detectTBOrderByTid(accessToken,13244355353535L+"");


    }
}
